Maximal Rectangle

Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.

Solution:

  1. public class Solution {
  2. public int maximalRectangle(char[][] M) {
  3. if (M == null || M.length == 0 || M[0].length == 0) {
  4. return 0;
  5. }
  6. int max = 0;
  7. int m = M.length;
  8. int n = M[0].length;
  9. int[][] H = new int[m][n];
  10. for (int i = 0; i < m; i++) {
  11. for (int j = 0; j < n; j++) {
  12. int v = getInt(M[i][j]);
  13. if (i == 0 || v == 0) {
  14. H[i][j] = v;
  15. } else {
  16. H[i][j] = v + H[i - 1][j];
  17. }
  18. }
  19. int res = largestRectangleArea(H[i]);
  20. max = Math.max(max, res);
  21. }
  22. return max;
  23. }
  24. public int largestRectangleArea(int[] A) {
  25. if (A == null) {
  26. return 0;
  27. }
  28. Stack<Integer> stack = new Stack<Integer>();
  29. int n = A.length, max = 0;
  30. for (int i = 0; i < n; i++) {
  31. while (!stack.isEmpty() && A[i] <= A[stack.peek()]) {
  32. int index = stack.pop();
  33. int left = stack.isEmpty() ? 0 : stack.peek() + 1;
  34. max = Math.max(max, A[index] * (i - left));
  35. }
  36. stack.push(i);
  37. }
  38. while (!stack.isEmpty()) {
  39. int index = stack.pop();
  40. int left = stack.isEmpty() ? 0 : stack.peek() + 1;
  41. max = Math.max(max, A[index] * (n - left));
  42. }
  43. return max;
  44. }
  45. private int getInt(char ch) {
  46. return (int)(ch - '0');
  47. }
  48. }